<template>
  <div>
    <base-modal :title="title" :show.sync="dialogVisible" width="500px" @close="closeDialog">
      <el-form class="pad-16" :model="ruleForm" ref="ruleForm" label-position="top" :rules="rules" v-loading="loading">
        <el-form-item v-if="!isFaultSource" :label="$t('faultLibrary.faultObject.label3')">
          <el-input disabled v-model="parentDesc"> </el-input>
        </el-form-item>
        <!-- 可选上级 -->
        <!-- <el-form-item 
        v-else
        :label="$t('faultLibrary.faultObject.label3')"
      >
        <label class="fault-source-label" slot="label" for="parentDesc">{{ $t('faultLibrary.faultObject.label3') }}</label>
        <div @click="showFaultDoalog" class="fault-source-ipt">{{ parentDesc }}</div>
      </el-form-item> -->

      <!-- 自定义标签 -->
        <el-form-item :label="$t('common.base.classification')">
          <div style="display: flex;">
						<el-input
							:maxlength="20"
							v-model="ruleForm.faultLabel"
							:placeholder="$t('common.faultLibrary.classificationPlaceholder')"
							@blur="ruleForm.faultLabel = ruleForm.faultLabel.trim()"
						>
						</el-input>
          </div>
        </el-form-item>

        <el-form-item :label="$t('common.base.title')" prop="faultDesc">
          <div style="display: flex;">
						<el-input
							v-model="ruleForm.faultDesc"
							:maxlength="100"
							:placeholder="$t('common.placeholder.input2')"
							@blur="ruleForm.faultDesc = ruleForm.faultDesc.trim()"
						>
						</el-input>
          </div>  
        </el-form-item>

        <el-form-item :label="$t('common.base.description1')" prop="faultContent">
          <div style="display: flex;">
						<el-input
							type="textarea"
							v-model="ruleForm.faultContent"
							:maxlength="5000"
							:placeholder="$t('common.base.tip.defaultPlaceholder')"
							:autosize="{ minRows: 2, maxRows: 6 }"
							@blur="ruleForm.faultContent = ruleForm.faultContent.trim()"
						>
						</el-input>
					</div>  
        </el-form-item>

        <el-form-item :label="$t('common.paas.formType.attachment')">
          <form-attachment :field="{isNull:1}" v-model="ruleForm.attribute.attachment"></form-attachment>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible = false">{{ $t('common.base.cancel') }}</el-button>
        <el-button type="primary" @click="submitForm" :loading="saveLoading">{{ isFromEnter ? $t('faultLibrary.startEnter') : $t('common.base.save') }}</el-button>
      </div>
    </base-modal>

    <!-- 选择故障清单弹窗 -->
    <!-- <choose-fault-dialog ref="chooseFaultDialog" @click="getParentData" /> -->
  </div>
</template>

<script>
// components
import ChooseFaultDialog from '@src/modules/task/editAllot/components/PartSeviceList/components/ChooseFaultDialog.vue';
// api
import { libraryCreate, libraryEdit, faultDetail } from '@src/api/Fault';
import * as FaultApi from '@src/api/Fault';
// util
import { message } from '@src/util/message';
import { findParents } from '@src/modules/faultLibrary/utils/index';
import MsgModel from '@model/MsgModel';
import i18n from '@src/locales';
import { cloneDeep } from 'lodash'
import { validateFaultDesc } from './common'

const baseData = {
  // 级别
  faultLevel: null,
  // 对象描述
  faultDesc: '',
  // 父级id
  parentId: '',
  // 自定义标签
  faultLabel: '',
  faultContent: '',
  attribute:{
    attachment:[]
  },
  descNameLanguage: {},
	contentNameLanguage: {},
	labelNameLanguage: {},
};

export default {
  // 故障描述
  name: 'FaultDescription',
  components: {
    // [ChooseFaultDialog.name]: ChooseFaultDialog
  },
  data() {
    
    return {
      loading: false,
      ruleForm: cloneDeep(baseData),
      // 上级故障描述
      parentDesc: '',
      // 上级祖链描述
      parentDescAll: '',
      saveLoading: false,
      rules: {
        faultDesc: [{ required: true, validator: validateFaultDesc, trigger: 'blur' }],
      },
    };
  },

  props: {
    value: {
      type: Boolean,
      default: false,
    },

    // 新建需要，记录父级id和当前级别
    createFaultData: {
      type: Object,
      default: () => ({}),
    },

    // 当前的id
    currentFaultDescriptionId: {
      type: String,
      default: '',
    },

    // 来源：0:故障树创建（默认）   1:工单附加组件创建（工单附加组件）
    faultSource: {
      type: Number,
      default: 0,
    },
    // 工单信息
    task: {
      type: Object,
      default: () => ({}),
    },
    isRegister: {
      type: Boolean,
      default: false,
    },
  },
  watch: {
    value(value) {
      if (!value) {
        this.initForm();
      }
    },
    dialogVisible(newValue){
      if(newValue === true){
        this.openDialog()
      }

    }
  },

  computed: {
    dialogVisible: {
      get() {
        return this.value;
      },

      set(val) {
        this.$emit('input', val);
      },
    },

    title: {
      get() {
        return this.isFromEnter ? this.$t('faultLibrary.enterFaultTree') : this.currentFaultDescriptionId ? this.$t('faultLibrary.faultObject.editTitle2') : this.$t('faultLibrary.faultObject.title2');
      },
    },
    // 工单附加组件创建
    isFaultSource() {
      return this.faultSource === 1;
    },
    isFromEnter() {
      return this.createFaultData.isStartEntry;
    },
  },

  methods: {
    initForm() {
      this.ruleForm = cloneDeep(baseData)
      // 上级故障描述
      this.parentDesc = '';
    },
    async openDialog() {
      // 新建
      if (!this.currentFaultDescriptionId) {
        const { parentId = null, faultLevel = null, parentDesc, faultLabel } = this.createFaultData || {};
        this.ruleForm.parentId = parentId;
        this.ruleForm.faultLevel = faultLevel;
        // this.ruleForm.faultLabel = faultLabel;
        this.parentDesc = parentDesc;
        return;
      }

      // 编辑

      this.loading = true;

      // 参数传递
      const params = { faultId: this.currentFaultDescriptionId };
      if (this.taskId) params.taskId = this.taskId;
      const res = await faultDetail(params);

      this.loading = false;

      const { id, parentId, faultLevel, faultLabel, faultDesc, parentDesc, faultContent, attribute } = res.data || {};

      // 编辑页面需要处理数据
      this.ruleForm.id = id;
      this.ruleForm.parentId = parentId;
      this.ruleForm.faultDesc = faultDesc;
      this.ruleForm.faultLabel = faultLabel;
      this.ruleForm.faultLevel = faultLevel;
      this.ruleForm.faultContent = faultContent;
      if(attribute){
        this.ruleForm.attribute = attribute
      }
      this.parentDesc = parentDesc;
    },

    closeDialog() {
      this.saveLoading = false;
      this.$refs.ruleForm.resetFields();
    },

    submitForm() {
      try {
        this.$refs.ruleForm.validate(async valid => {
          if (!this.parentDesc) return message.warning(this.$t('common.faultLibrary.pleaseSelectSuperiorFault'));
          if (!valid) return;

          this.saveLoading = true;

          let params = {
            ...this.ruleForm,
            faultSource: this.faultSource,
            enterState: this.faultSource === 1 ? 0 : 1,
          };

          const port = this.currentFaultDescriptionId ? libraryEdit : libraryCreate;
          const res = await port(params);

          if (res.status !== 0) {
            this.$notify.error({
              title: this.$t('common.base.toast'),
              message: res.message,
              duration: 2000,
            });
            return;
          }

          if (this.task.id) {
            // 绑定工单
            const params1 = {
              taskId: this.task.id,
              taskNo: this.task.taskNo,
              faultId: res.data.id,
              faultDesc: this.parentDescAll ? `${this.parentDescAll}/` + res.data.faultDesc : res.data.faultDesc,
              objDesc: this.createFaultData.objDesc,
            };
            if (this.createFaultData.id) params1.id = this.createFaultData.id;

            await this.faultBindTask(params1, this.currentFaultDescriptionId);
          }

          // 关闭弹窗
          this.dialogVisible = false;

          this.$emit('operateSuc', { ...res.data, parentDescAll: this.parentDescAll, isEdit: !!this.currentFaultDescriptionId });
        });
      } catch (err) {
        console.log('submitForm => err', err);
      } finally {
        this.saveLoading = false;
      }
    },
    // 绑定工单
    faultBindTask(params, isEdit = false) {
      let url = 'getTaskCardSave';
      if (isEdit) {
        url = 'getTaskCardEdit';
      }
      FaultApi[url](params)
        .then(res => {
          if (!MsgModel.isSuccess(res)) return message.error(res.message);
        })
        .catch(error => {
          console.log('faultBindTask: ', e);
        });
    },
    showFaultDoalog() {
      this.$refs.chooseFaultDialog.open({
        isSelectParent: true, // 是否在选上级
        defaultCheckedKeys: [this.ruleForm.parentId],
      });
    },
    // 选择上级
    getParentData(data) {
      this.ruleForm.parentId = data.id;
      this.ruleForm.faultLevel = data.faultLevel + 1;
      this.parentDesc = data.faultDesc;
      this.parentDescAll = data.parentDescAll;
    },
    saveDesc(data) {
			this.ruleForm.faultDesc = data[i18n.locale];
			this.ruleForm.descNameLanguage = data;
		},
		saveContent(data) {
			this.ruleForm.faultContent = data[i18n.locale];
			this.ruleForm.contentNameLanguage = data;
		},
		saveLabel(data) {
			this.ruleForm.faultLabel = data[i18n.locale];
			this.ruleForm.labelNameLanguage = data;
		},
  },
};
</script>

<style lang="scss" scoped>
.el-form {
  .fault-source-label {
    position: relative;
  }

  .fault-source-label::before {
    content: '*';
    color: #f56c6c;
    margin-right: 4px;
  }

  .fault-source-ipt {
    width: 100%;
    border-radius: 4px;
    border: 1px solid $border-color-base;
    min-height: 30px;
    padding-left: 8px;
    line-height: 28px;
    cursor: pointer;
  }
}
</style>
